from urllib.parse import urlencode

from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from mall import settings
from oauth.models import OAuthQQUser
from oauth.seriazer import QQRegisterSeriazer
from oauth.utils import OauthQQ
from rest_framework_jwt.settings import api_settings


class QQAuthURLView(APIView):
    # 实现出现ＱＱ授权登录视图  /oauth/qq/statues
    def get(self, request):
        # 获取state
        state = request.query_params.get('state')
        # 设置base_url
        qq=OauthQQ()
        # return auth_url
        auth_url=qq.get_oauth_url(state)

        # 返回响应  设置接口
        #登陆回调

        return Response({'auth_url': auth_url})
#用到序列化器
class QQTokenView(GenericAPIView):
    #通过ｃｏｄｅ获取ｔｏｋｅｎ
    """
       获取access_token
       GET /oauth/qq/users/?code=xxx
       """


    def get(self,request):
        #获取ｃｏｄｅ，进行判断
        code=request.query_params.get('code')
        if code is None:
            return Response({'message':'缺少参数'},status=status.HTTP_400_BAD_REQUEST)
        qq=OauthQQ()
        try:
            access_token=qq.get_access_token(code)
            openid=qq.get_openid(access_token)
        except Exception:

            return Response({'message':'服务异常'},status=status.HTTP_404_NOT_FOUND)
        try:
            qq_user=OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            #不存在就是第一次授权登陆的
            token=OAuthQQUser.generate_save_user_token(openid)
            return Response({'access_token':token})
        else: #查询用户,生成登录token
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            #
            # response = Response({
            #     'token': token,
            #     'user_id': user.id,
            #     'username': user.username
            # })
            return Response({
                'token': token,
                'user_id': user.id,
                'username': user.username

            })


    serializer_class=QQRegisterSeriazer

    def post(self, request):
            serializer= self.get_serializer(data=request.data)
            serializer.is_valid()
            user=serializer.save()

            # 查询用户　生成登陆ｔｏｋｅｎ
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 载荷

            payload = jwt_payload_handler(user)
            # 编码
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'user_id': user.id,
                'username': user.username

            })
